import { hexmd5 } from '@/utils/md5'
const APP_SECRET = process.env.VUE_APP_SIGNATURE_SECRET

export function getSignature(requestUrl, requestParam) {
  if (requestUrl == null) {
    return ''
  }

  // 根据请求匹配请求参数并去除“=”构成数组
  let paramArr = getQueryString(requestUrl)
  if (paramArr.length <= 0) {
    paramArr = []
  }

  for (const k in requestParam) {
    if (Object.hasOwnProperty.call(requestParam, k) && k !== 'sign') {
      // null值替换为空字符串
      if (requestParam[k] === null) {
        paramArr.push([k, ''])
        continue
      }
      // 判断requestParam[k]类型: 取消file类型数据加入到签名中
      if (requestParam[k] === undefined) {
        continue
      }
      if (requestParam[k] instanceof Array) {
        const vaule = JSON.stringify(requestParam[k])
        paramArr.push([k, vaule])
      } else {
        paramArr.push([k, (requestParam[k] + '').trim()])
      }
    }
  }

  // 请求参数排序
  paramArr.sort()

  // 对参数进行过滤
  const filterParamArr = []
  paramArr.forEach(param => {
    if (param instanceof Array) {
      filterParamArr.push(param.join(''))
    }
  })

  // 携带secret
  // console.log(filterParamArr.join(''))
  const signature = filterParamArr.join('') + APP_SECRET
  // 返回md5加密的签名
  return hexmd5(signature)
}

function getQueryString(requestUrl) {
  const result = requestUrl.match(/^[?&]([^?&=]+)=([^?&=]*)'$/, 'g')

  if (result == null) {
    return ''
  }

  for (let i = 0; i < result.length; i++) {
    // 去除请求参数前后的空格
    const resultArr = result[i].split('=')
    result[i] = resultArr[0].trim() + resultArr[1].trim()
    result[i] = result[i].substring(1)
    result[i] = result[i].split('=')
  }

  return result
}
